const exec = require('./exec')
const utils = require('./utils')
const init = require('./refresh');
const fs = require('fs');
const cmd = require('child_process');
const config = require('./env');

let SESSIONIDD2 = fs.readFileSync('session','utf8');
const log4js = require('log4js');
log4js.configure({
	appenders: { cheese: { type: "file", filename: "buy.log" } },
	categories: { default: { appenders: ["cheese"], level: "error" } }
});
const logger = log4js.getLogger();
logger.level = "debug";
async function main(orderId,price) {
	SESSIONIDD2 = fs.readFileSync('session','utf8');
	const res = await utils.request(`https://api.stepn.com/run/buyprop?orderID=${orderId}&price=${price}`,{},'get',SESSIONIDD2);
	console.log(res);
	if(res.code === -2) {
		relogin();
		return;
	}else{
		await utils.sleep(5000);
		let result = {
			code:-1000,
			msg:'鞋子购买失败',
			data:null
		}
		if (res.code === 0) {
			result = await shoeList();
			// result1 = await userInfo();
			// if(result1.code === 0) {

			// }
		}
		logger.debug(`购买Id：${orderId} - 购买价格：${price} - 购买结果：${res.code === 0 ? '成功' : '失败'} - 支付额外信息：${res.code === 0 ? '无' : res.msg}`);
		utils.postMessage(config.hook,{
			msg_type:'post',
			content:{
				post:{
					"zh_cn":{
						title:"购买结果",
						content:[
							[
								{
									tag:'text',
									"un_escape":true,
									text:res.code === 0 ? '支付结果：成功\n' :'支付结果：失败\n',
								}
							],
							[
								{
									tag:'text',
									"un_escape":true,
									text:`支付价格：${price/1000000}`,
								}
							],
							[
								{
									tag:'text',
									"un_escape":true,
									text:`转移到钱包：${result.code === 0 ? '成功' : '失败'}`,
								}
							],
							[
								{
									tag:'text',
									"un_escape":true,
									text:`转移额外信息：${result.code === 0 ? '无' : result.msg}`,
								}
							],
							[
								{
									tag:'text',
									"un_escape":true,
									text:`支付额外信息：${res.code === 0 ? '无' : res.msg}`,
								}
							],
							// [
							// 	{
							// 		tag:'text',
							// 		"un_escape":true,
							// 		text:`账户余额：${result1.code === 0 ? ' SOL：'+result1.data.asset. : '暂无信息'}`,
							// 	}
							// ]
						]
					}
				}
			}
		});
	}
}
async function userInfo() {
	return await utils.request('https://api.stepn.com/run/userbasic',{},'get',SESSIONIDD2);
}
function relogin() {
	let i = 0;
	const timer = setInterval(() =>{
		const res = fs.readFileSync('session','utf8')
		if(SESSIONIDD2 !== res) {
			clearInterval(timer);
			SESSIONIDD2 = res;
			main();
		}
		if(i>=10) {
			console.log('获取新的SESSION超时');
			clearInterval(timer);
			main();
		}
		i++
	},5000);
	exec.launchApp();
}
async function shoeList() {
	const res = await utils.request('https://api.stepn.com/run/shoelist?page=0',{},'get',SESSIONIDD2);
	console.log(res);
	if(res.code === 0) {
		const item = res.data[0];
		return transform(item['dataID'],item['id'],item['chain']);
	}
	return {
		code:-1000,
		msg:'获取鞋子列表失败',
		data:null
	};
}
async function transform(dataId,propId,chainId) {
	const res = await utils.request(`https://api.stepn.com/run/withdrawtoken?dataID=${dataId}&propID=${propId}&chainID=${chainId}&num=1`,{},'get',SESSIONIDD2);
	console.log(res);
	return res;
}
const Koa = require('koa');
const app = new Koa();
app.use(async ctx => {
	if(ctx.path === '/buy') {
		const {orderId,price} = ctx.query;
		main(orderId,price);
		ctx.body = "操作成功，请返回飞书查看购买结果通知";
	}
	if(ctx.path === '/refresh') {
		if(fs.readFileSync('status','utf8') === 'false') {
			ctx.body = "上次任务还未结束，无法开始新的请求";
			return;
		}
		init();
		fs.writeFileSync('status','false','utf8');
		ctx.body = "请求数据成功，请返回飞书等待2-3分钟后推送";
	}
});
app.listen(80);